package cn.droidlover.xdroidmvp.mvp;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;

import androidx.annotation.ColorRes;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.List;
import butterknife.Unbinder;
import cn.droidlover.xdroidmvp.R;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.kit.KnifeKit;
import cn.droidlover.xdroidmvp.util.EmptyUtil;
import cn.droidlover.xdroidmvp.util.ScreenUtils;
import cn.droidlover.xdroidmvp.view.widget.ColorDividerDecoration;
import cn.droidlover.xdroidmvp.view.NotRecordView;

/**
 * Activity 基类  需要刷新的activity
 * <p>
 * 1.切换语言
 * 2.切换日夜模式
 * 3.检测横竖屏
 * 4.显示/隐藏Loading弹框
 * 5.ButterKnife 绑定数据
 * 6.控制RxJava生命周期，防止内存泄漏
 * 7.MVP模式 参考 https://github.com/north2016/T-MVP
 * 需要时 可重写createPresenter() {@link RefreshActivity#()}  并且使用泛型 <P extends BasePresenter> 为当前Presenter实例
 */

public abstract class RefreshActivity<P extends IPresent> extends BaseActivity
        implements BaseQuickAdapter.RequestLoadMoreListener,IView<P>   {

    private P p;
    private Unbinder unbinder;
    private View mContextView;

    //默认需要设置paddingTop高度为状态栏高度
    private boolean shouldPaddingTop = false;

    /*** 每页请求数量 */
    public int PAGE_COUNT = 10;
    /*** 页码，默认从1开始 */
    protected int PageStart = 1;
    protected int mPage = 1;
    /*** 空布局类型 可以在这里设置默认值 */
    protected int emptyType = 1;
    /*** 是否启用空布局 */
    private boolean enableEmptyView = false;
    protected boolean isLoadEnd;//是否已经加载完了，没有更多数据了

    protected SmartRefreshLayout mRefreshLayout;
    protected RecyclerView mRecyclerView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getP();
        if (getLayoutId() > 0) {
            mContextView = bindLayout();
            setContentView(mContextView);
            bindUI(null);
            bindEvent();
        }

        initData(savedInstanceState);
    }


    @Override
    public Context getContext() {
        return context;
    }

    @Override
    public void bindUI(View rootView) {
        unbinder = KnifeKit.bind(this);
    }

    private View bindLayout() {
        return  LayoutInflater.from(this).inflate(getLayoutId(), null);
    }

    protected P getP() {
        if (p == null) {
            p = newP();
        }
        if (p != null) {
            if (!p.hasV()) {
                p.attachV(this);
            }
        }
        return p;
    }

    @Override
    protected void onStart() {
        super.onStart();
        int statusBarHeight = ScreenUtils.getStatusBarHeight(this);
        //动态设置状态栏高度
        if (shouldPaddingTop) {
            mContextView.setPadding(0, statusBarHeight, 0, 0);
        }
        if (useEventBus()) {
            BusProvider.getBus().register(this);
        }
    }

    protected void setShouldPaddingTop(boolean shouldPaddingTop) {
        this.shouldPaddingTop = shouldPaddingTop;
    }



    @Override
    public boolean useEventBus() {
        return false;
    }

    @Override
    public P newP() {
        return null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (getOptionsMenuId() > 0) {
            getMenuInflater().inflate(getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (useEventBus()) {
            BusProvider.getBus().unregister(this);
        }
        if (getP() != null) {
            getP().detachV();
        }
        p = null;
        KnifeKit.unbind(unbinder);
    }




    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    @Override
    public void bindEvent() {

    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }



    /***********************        MVP 参考 刷新框架        ***************************/

    /**
     * 设置刷新框架，需要时调用即可
     */
    protected void initRefreshLayout() {
        mRefreshLayout = (SmartRefreshLayout) findViewById(R.id.mRefreshLayout);
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableRefresh(true);
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.setEnableAutoLoadMore(false);
            mRefreshLayout.setDisableContentWhenLoading(true);
            mRefreshLayout.setDisableContentWhenRefresh(true);
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    RefreshActivity.this.onRefresh();
                }
            });
        }
    }

    /**
     * 开关刷新
     *
     * @param enableRefresh
     */
    public void setEnableRefresh(boolean enableRefresh) {
        if (mRefreshLayout != null)
            mRefreshLayout.setEnableRefresh(enableRefresh);
    }

    /**
     * 初始化列表控件
     */
    protected void initRecyclerView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
    }

    public void setPageCount(int pageCount) {
        PAGE_COUNT = pageCount;
    }

    public void setPageStart(int pageStart) {
        PageStart = pageStart;
    }

    /**
     * 设置分割线
     *
     * @param colorId
     */
    protected void addItemDecoration(@ColorRes int colorId) {
        if (mRecyclerView != null) {
            mRecyclerView.addItemDecoration(new ColorDividerDecoration(ContextCompat.getColor(this, colorId)));
        }
    }

    protected void addItemDecoration(@ColorRes int colorId, int dp) {
        if (mRecyclerView != null) {
            // mRecyclerView.addItemDecoration(new ColorDividerDecoration(ContextCompat.getColor(context, colorId), ScreenUtils.dp2px(context, dp)));
        }
    }

    protected void addItemDecoration() {
        //设置默认分割线
        if (mRecyclerView != null) {
            mRecyclerView.addItemDecoration(new ColorDividerDecoration(Color.parseColor("#f4f4f4")));
        }
    }


    /**
     * 自动刷新
     */
    public void autoRefresh() {
        if (mRefreshLayout != null)
            mRefreshLayout.autoRefresh();
    }

    /**
     * 结束刷新
     */
    public void finishRefresh() {
        if (mRefreshLayout != null)
            mRefreshLayout.finishRefresh(0);
    }


    /***
     * 是否启用空布局
     * @param enableEmptyView
     */
    public void setEnableEmptyView(boolean enableEmptyView) {
        this.enableEmptyView = enableEmptyView;
    }

    public void setEnableEmptyView(boolean enableEmptyView, int emptyType) {
        this.enableEmptyView = enableEmptyView;
        this.emptyType = emptyType;
    }


    public void setLoadData(BaseQuickAdapter adapter, List<?> list) {
        setLoadData(adapter, list, emptyType);//emptyType 可以给一个默认值,作为统一设置
    }

    /**
     * 不分页的 设置数据
     *
     * @param adapter
     * @param list
     * @param emptyType
     */
    public void setLoadData(BaseQuickAdapter adapter, List<?> list, int emptyType) {
        this.emptyType = emptyType;
        adapter.setHeaderFooterEmpty(true, true);//是否显示头部和底部

        finishRefresh();
        adapter.setNewData(list);
        if (EmptyUtil.isEmpty(list)) {
            setEmptyView(adapter);
        }
    }


    public void setLoadMore(BaseQuickAdapter adapter, List<?> list) {
        setLoadMore(adapter, list, emptyType);
    }

    /**
     * 如果使用的是当前的 mRecyclerView
     *
     * @param adapter
     * @param list
     * @param emptyType
     */
    public void setLoadMore(BaseQuickAdapter adapter, List<?> list, int emptyType) {
        if (mRecyclerView != null) {
            setLoadMore(mRecyclerView, adapter, list, emptyType);
        }
    }


    /**
     * 结束刷新
     * 自动设置上拉更多
     *
     * @param adapter
     * @param list
     */
    public void setLoadMore(RecyclerView recyclerView, BaseQuickAdapter adapter, List<?> list, int emptyType) {
        this.emptyType = emptyType;
        adapter.setHeaderFooterEmpty(true, true);//是否显示头部和底部

        finishRefresh();//结束刷新
        if (mPage == PageStart) {
            isLoadEnd = false;
            adapter.setNewData(list);
            if (EmptyUtil.isEmpty(list)) {
                isLoadEnd = true;
                setEmptyView(adapter);
            }
        } else {
            if (list != null && !list.isEmpty()) {
                adapter.addData(list);
            }
        }

        if (list == null || list.size() < PAGE_COUNT) {
            isLoadEnd = true;
            adapter.loadMoreEnd();
        } else {
            adapter.setEnableLoadMore(true);
            adapter.setOnLoadMoreListener(this, recyclerView);
            adapter.loadMoreComplete();
        }
    }

    /**
     * 设置空状态
     * <p>
     * 根据项目情况 自由定制
     *
     * @param adapter
     */
    protected void setEmptyView(BaseQuickAdapter adapter) {

        if (enableEmptyView) {
            NotRecordView view = new NotRecordView(getContext());
            view.setType(emptyType);
            adapter.setEmptyView(view);
        }
    }
    /**
     * 结束刷新
     */
    @Override
    public void onRequestFinish() {
        finishRefresh();
    }

    public void onRefresh() {
        mPage = 1;
        loadData();
    }

    /**
     * 如需上拉更多 请重写该方法
     */
    @Override
    public void onLoadMoreRequested() {
        mPage++;
        loadData();
    }


    protected void loadData(){};


}
